<template>
  <PageWrapper>
<!--    <div class="lg:flex">-->
<!--      <div class="lg:w-2/10 w-full !mr-4 enter-y" >-->
    <div :class="{ 'textSelect': textDisable}" :style="winWidth">
      <div style="display: inline-block;vertical-align: top;" :style = "leftClass">
        <Card class="!my-4 enter-y" :style="cardHeight" style="overflow-y: scroll">
          <ElTree ref="treeRef" :data="treeData" node-key="childNodeCode" :default-expanded-keys="expandNodes" :props="defaultProps" @node-click="handleNodeClick" highlight-current>
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <span>{{ node.label }}</span>
              </span>
            </template>
          </ElTree>
          <Loading :loading="treeLoading" absolute="true" :tip="loadingText"/>
        </Card>
      </div>
<!--      <div class="lg:w-8/10 w-full enter-y">-->
      <div class="draggable" style="width: 5px; display: inline-block;vertical-align: top;" :style="cardHeight"></div>
      <div style="display: inline-block;vertical-align: top;" :style = "rightClass">
        <Card class="!my-4 enter-y common_style" :style="cardHeight">
          <div style="background-color: #daecf8; padding-top: 10px">
            <el-form style="margin-left: 0px ;margin-bottom: 0px " :model="form">
            <el-row>
              <el-col :span="8">
                <el-form-item  label="一级区域">
                  <el-select v-model="form.firstRegion" filterable placeholder="  "  clearable style="width: 100%">
                    <el-option v-for="op in firstRegionOptions" :key="op" :value="op" :label="op" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="二级区域">
                  <el-select v-model="form.secondRegion" filterable placeholder="  "  clearable style="width: 100%">
                    <el-option v-for="item in filterSecondRegions" :key="item.secondLevel" :value="item.secondLevel" :label="item.secondLevel" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="通用/专用类型">
                  <el-select v-model="form.type" filterable placeholder="  " clearable style="width: 100%">
                    <el-option v-for="op in productTypeOptions" :key="op" :value="op" :label="op" />
                  </el-select>
                </el-form-item>
              </el-col>

            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="产品大类">
                  <el-select v-model="form.productCategory" filterable placeholder="  " clearable style="width: 100%">
                    <el-option v-for="op in productCategoryOptions" :key="op.productCategory" :value="op.productCategory" :label="op.productCategory" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="产品系列">
                  <el-select v-model="form.productSeries" filterable placeholder="  " clearable style="width: 100%">
                    <el-option v-for="op in filterProductSeries" :key="op.productSeries" :value="op.productSeries" :label="op.productSeries" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8" >
                <el-button type="primary" style="margin-left: 50px; background: #6096e6" @click="selectData">查询</el-button>
              </el-col>
            </el-row>
          </el-form>
          </div>

          <div style="position: relative">
            <el-table id="saleProduct" v-if="nodeCode !=='' && nodeCode !== null" max-height="500px" :data="tableData" :cell-style="cellStyle" :header-cell-style="headerStyle" border style="width: 100%; background-color: #daecf8">
              <el-table-column prop="productNumber" label="产品编码" width="150" />
              <el-table-column prop="model" label="产品型号" width="180" />
              <el-table-column prop="productName" label="产品名称" />
              <el-table-column prop="state" label="状态" width="150"/>
              <el-table-column prop="version" label="版本" width="120"/>
            </el-table>
            <el-table
              id="saleOffering"
              v-else
              max-height="500px" ref="expandTable"
              :cell-style="specialCellStyle"
              :header-cell-style="headerStyle"
              :row-key="getRowKey"
              :expand-row-keys="expandKeys"
              :data="secondTableData"
              :border="true"
              @cell-click="handleCellEvent"
              style="width: 100%; background-color: #daecf8">
              <el-table-column style = "padding: unset" label="" width="1px" type="expand">
                <template #default="{row}">
                  <el-table :data="row.productList" :cell-style="cellStyle" :header-cell-style="headerStyle" border style="width: 100%">
                    <el-table-column prop="productNumber" label="产品编码" width="180" />
                    <el-table-column prop="model" label="产品型号" width="240" />
                    <el-table-column prop="productName" label="产品名称"/>
                    <el-table-column prop="state" label="状态" width="150"/>
                    <el-table-column prop="version" label="版本" width="120"/>
                  </el-table>
                  <Loading :loading="row.subSaleLoading" absolute="true" :tip="loadingText"></Loading>
                </template>
              </el-table-column>
              <el-table-column  prop="" label="" width="50">
                <template #default="{row}">
                  <div>
                      <span  @click="iconClick(row)">
                         <el-icon v-if="!row.expanded" color="#000000"><Plus /></el-icon>
                         <el-icon v-else color="#000000"><Minus /></el-icon>
                      </span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column  prop="board" label="板块" width="130">
                <template #default="scope">
                  <div> {{ scope.row.board }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="firstLevelRegion" label="一级区域" width="120" />
              <el-table-column prop="secondLevelRegion" label="二级区域" width="120"/>
              <el-table-column prop="industry" label="通用/专用类型" width="150"/>
              <el-table-column prop="productCategory" label="产品大类"/>
              <el-table-column prop="productSeries" label="产品系列名"/>
              <el-table-column prop="offeringName" label="Offering" width="270">
                <template #default="{row}">
                  <el-link  type="primary">{{row.offeringName}}</el-link>
                </template>
              </el-table-column>
            </el-table>
            <Loading :loading="saleLoading" absolute="true" :tip="loadingText"></Loading>
          </div>
        </Card>
      </div>
    </div>
  </PageWrapper>
</template>
<script lang="ts" setup>
import {computed, nextTick, ref, watch} from 'vue';
  import { Card } from 'ant-design-vue';
  import { PageWrapper } from '/@/components/Page';
  import * as API from '@/api/pbi/sale';
import * as APIOffering from '@/api/pbi/offering';
import {ElTree} from "element-plus";
import { Loading } from '/@/components/Loading';
import {
  deepClone,
  endLoading,
  getHeaderStyle,
  getSpecialCellStyle,
  getTableCellStyle, loading,
  startLoading
} from "@/utils";
import {Minus} from "@element-plus/icons-vue";
import {useGlobSetting} from "@/hooks/setting";
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
const router = useRouter()
  const headerStyle= ref(getHeaderStyle());
  const cellStyle= ref(getTableCellStyle());
const specialCellStyle= ref(getSpecialCellStyle());
const secheaderStyle= ref({
  'text-align': 'center'
});
  const treeLoading = ref(false);
  const saleLoading = ref(false);
  const loadingText = ref('数据正在加载中...');
const expandNodes = ref([]);


const  productTypeMap = ref({
  '低压': 1,
  '中压': 2,
  '高压': 3,
  '伺服': 4,
  '电机': 5,
  '控制器产品': 6,
  '触摸屏': 7,
  'PLC': 8,
  'I/O': 9,
  '电梯': 10,
  '工业互联网产品线': 11
})

  interface Tree {
    parentNodeCode: string;
    parentNodeName: string;
    parentNodeType: string;
    childNodeCode: string;
    childNodeName: string;
    level: number;
    children?: Tree[];
  }
  const defaultProps = {
    children: 'children',
    label: 'childNodeName',
  };

  const form = ref({
    firstRegion: "",
    secondRegion: "",
    type: "",
    productCategory: "",
    productSeries: ""
  })

  const firstRegionOptions = ref([]);
  const allSecondRegionOptions = ref([]);
  const filterSecondRegions = computed(()=> {
    if (form.value.firstRegion === '') {
      return allSecondRegionOptions.value;
    }
    return allSecondRegionOptions.value.filter(a=> a.firstLevel === form.value.firstRegion)
  })
  watch(()=> form.value.firstRegion,()=> {
    form.value.secondRegion = ''
  })
  const productTypeOptions = ref(['通用','专用']);
  const productCategoryOptions = ref([]);
  const allProductCategoryOptions = ref([]);
  // const filterProductCategorys = computed(()=> {
  //   if (allProductCategoryOptions.value.filter(a=> a.productType === form.value.type).length >0) {
  //     let category = allProductCategoryOptions.value.filter(a=> a.productType === form.value.type)[0];
  //     return category.nodes;
  //
  //   }
  // return [];
  //  });
  // watch(()=> form.value.type,()=> {
  //   form.value.productCategory = '';
  //   form.value.productSeries = '';
  // })
const filterProductSeries = computed(()=> {
  // if (allProductCategoryOptions.value.filter(a=> a.productType === form.value.type).length >0) {
  //   let type = allProductCategoryOptions.value.filter(a=> a.productType === form.value.type)[0];
  //   if (type.nodes.filter(b=> b.productCategory === form.value.productCategory).length > 0) {
  //     let category = type.nodes.filter(b=> b.productCategory === form.value.productCategory)[0];
  //     return category.nodes;
  //   }
  //   return [];
  // }
  if (form.value.productCategory === '') {
    let tempList = [];
    productCategoryOptions.value.forEach(category=> {
      if (category.nodes && category.nodes.length >0) {
        category.nodes.forEach(node=> {
          tempList.push(node)
        })
      }
    })
    // console.log(tempList)
    return Array.from(new Set(tempList))
  }
  if (productCategoryOptions.value.filter(b=> b.productCategory === form.value.productCategory).length > 0) {
    let category = productCategoryOptions.value.filter(b=> b.productCategory === form.value.productCategory)[0];
    return category.nodes;
  }
  return [];
});
watch(()=> form.value.productCategory,()=> {
  form.value.productSeries = ''
})
const treeRef = ref<InstanceType<typeof ElTree>>()

  const treeData=ref([]);

  const tableData = ref([
  ]);

  const secondTableData = ref([
  ]);

  const selectData = ()=> {
    //必填校验
    if (form.value.firstRegion) {
      if (form.value.secondRegion === '') {
        ElMessage({
          message: '请选择二级区域！',
          type: 'warning',
        })
        return
      }
    }

    // if (form.value.productCategory) {
    //   if (form.value.productSeries === '') {
    //     ElMessage({
    //       message: '请选择产品系列！',
    //       type: 'warning',
    //     })
    //     return
    //   }
    // }

    nodeCode.value = '';
    expandKeys.value = []
    saleLoading.value = true;
    // startLoading('#saleOffering')
    API.searchSalesCatelog(form.value).then(res => {
      console.log('oool')
      console.log(res)
      if (res && res.success === 'true') {
        secondTableData.value = JSON.parse(res.data);
      }
    }).finally(()=> {
      saleLoading.value = false
      // endLoading()
    });

  }
  const loadOptions = async () => {
    const res = await API.getSalesCatelogQueryCondition();
    let regionInfo = [];
    let typeInfo = [];
    let productType = [];
    if (res && res.success === 'true') {
      let data = res.data;
      data.forEach(item=> {
        const keys = Object.keys(item);
        if (keys.includes("区域")) {
          regionInfo = item["区域"]
        } else if (keys.includes("productType")) {
          typeInfo.push(item);
          productType.push(item['productType']);
        }
      });
    }
    allSecondRegionOptions.value = regionInfo;
    allProductCategoryOptions.value = typeInfo;
    firstRegionOptions.value = Array.from(new Set(regionInfo.map(a=> a.firstLevel)));
    productTypeOptions.value = Array.from(new Set(productType));
    let productTypeInfo = typeInfo.find(a=> a.nodes.length > 0);
    if (productTypeInfo) {
      productCategoryOptions.value = productTypeInfo.nodes;
    }
  };

// 递归函数
const dg = function(list, res) {
  list.forEach(item=> {
    const itemCh = res.filter(a => a.childNodeCode != '' && a.childNodeCode != null && a.parentNodeCode == item.childNodeCode)
    if (itemCh && itemCh.length >0) {
      itemCh.sort((a,b) => a.childNodeName.localeCompare(b.childNodeName))
      item.children = itemCh;
      // 再次调用dg这个函数 再走一遍
      dg(item.children, res);
    }
  })
}

  const winWidth = computed(() => {
    let winWidth = window.innerWidth-30;
    let winHeight = window.innerHeight - 70;
    return {
      width: winWidth + 'px',
      height: winHeight + 'px',
    };
  });
  const cardHeight = computed(() => {
    let winHeight = window.innerHeight - 70;
    return {
      height: winHeight + 'px',
    };
  });

const initTree = async () => {
  treeLoading.value = true
  try {
    const {saleRootId} = useGlobSetting();
    const res = await API.getSalesCatelogTree({salesCatelogNumber: saleRootId});
    if (res && res.success === 'true') {
      console.log(res.data);
      let result = JSON.parse(res.data)
      const level1List = result.filter(a => a.parentNodeCode == saleRootId)
      if (level1List && level1List.length > 0) {
        // 排序
        level1List.sort((a,b) => a.childNodeName.localeCompare(b.childNodeName));
        dg(level1List, result);
        //构造根对象
        const rootNode = {
          "parentNodeCode": "",
          "parentNodeName": "",
          "parentNodeType": "",
          "childNodeCode": level1List[0].parentNodeCode,
          "childNodeName": level1List[0].parentNodeName,
          "level": 0,
          "children": level1List
        }
        console.log(rootNode)
        treeData.value.push(rootNode)
        expandNodes.value.push(rootNode.childNodeCode)
        level1List.forEach(item=> {
          expandNodes.value.push(item.childNodeCode)
          if (item.children && item.children.length > 0) {
            item.children.forEach(subItem=> {
              expandNodes.value.push(subItem.childNodeCode)
              subItem.children.forEach(threeItem=> {
                if (threeItem.children && threeItem.children.length > 0) {
                  //排序
                  let tempList = [];
                  tempList = deepClone(threeItem.children);
                  tempList.forEach(tmp=> tmp.saId = productTypeMap.value[tmp.childNodeName] != null ? productTypeMap.value[tmp.childNodeName] : 20);
                  tempList.sort((a, b) => a.saId - b.saId);
                  threeItem.children = tempList;
                }

              })
            })
          }
        })
        nextTick(()=>{
          addWatch();
        })
      }
      console.log('dwfw7777777777777777777')
      console.log(treeData.value)
    }
  } finally {
    treeLoading.value = false
  }

}
initTree();
  loadOptions();
const nodeCode = ref<String>('');

const handleNodeClick = async (data: Tree) => {
  //清空上一个节点的数据
  form.value.firstRegion = '';
  form.value.secondRegion = '';
  form.value.type = '';
  form.value.productCategory = '';
  form.value.productSeries = '';
  tableData.value = [];
  secondTableData.value = [];
  if (data.children == null || data.children.length == 0) {
    nodeCode.value = data.childNodeCode;
    //调用第一个子组件的方法
    console.log("你点击了销售目录的节点");
    // startLoading('#saleProduct')
    saleLoading.value = true;
    // 加载数据
    try {
      const res = await APIOffering.getOfferingProduct({pbinumber: nodeCode.value});
      if (res && res.success === 'true') {
        tableData.value = JSON.parse(res.data)
      }
    } finally {
      // endLoading()
      saleLoading.value = false;
    }
  }
  // nextTick(()=>{
  //   addWatch();
  // })
  console.log(data);
};
const getRowKey = (row)=> {
  return row.offeringNumber;
}

const expandKeys = ref([]);

const iconClick = async (row) => {
  const index = expandKeys.value.indexOf(row.offeringNumber);
  row.expanded = !row.expanded
  if (index >= 0) {
    expandKeys.value.splice(index, 1);
  } else {
    expandKeys.value.push(row.offeringNumber);
    // startLoading('# ' + row.offeringNumber)
    row.subSaleLoading = true;
    try {
      const res = await APIOffering.getOfferingProduct({
        pbinumber: row.offeringNumber
      });
      if (res && res.success === 'true') {
        row.productList = JSON.parse(res.data)
      }
    } finally {
      // setTimeout(()=> {
      //   row.subSaleLoading = false;
      // }, 3000)
      row.subSaleLoading = false;
      // endLoading()
    }
  }
  // this.$refs.expandTable.toggleRowExpansion(row, row.expanded);
  // console.log("点击")
}

const handleCellEvent = (row, column, cell, event)=> {
  console.log(row);
  console.log(column);
  console.log(cell);
  console.log(event);
  if (column.property == 'offeringName') {
    //路由跳转
    let offeringNumber = row.offeringNumber;
    router.push({name: 'Product', query: {pbinumber: offeringNumber}})
  }
}

const textDisable = ref<boolean>(false)
const leftWidth = ref<number>((window.innerWidth - 30) * 0.15)
const rightWidth = ref<number>()
const leftClass = computed(() => {
  return {
    width: leftWidth.value + 'px',
  };
});
const rightClass = computed(() => {
  let winWidth = window.innerWidth-30 -leftWidth.value-5;
  return {
    width: winWidth + 'px',
  };
});
nextTick(()=> {
  let draggable = document.querySelector('.draggable');
  draggable.onmousedown = function (e) {
    let startX = e.clientX;
    let startLeft = leftWidth.value;
    textDisable.value = true
    document.onmousemove = function (e) {
      // 在这里处理拖动事件
      let offset = e.clientX - startX

      if (startLeft + offset > (window.innerWidth - 30) * 0.3) {
        leftWidth.value = (window.innerWidth - 30) * 0.3
      } else if (startLeft + offset < (window.innerWidth - 30) * 0.15) {
        leftWidth.value = (window.innerWidth - 30) * 0.15
      } else {
        leftWidth.value = startLeft + offset;
      }
    }
    document.onmouseup = function (ev) {
      ev.stopPropagation()
      document.onmousemove = null;
      document.onmouseup = null
      textDisable.value = false
    };
  };
})
// const treeRef = ref(null);
const addWatch = ()=>{
  let elTree = treeRef.value.$el
  if (elTree != null) {
    let elNode = elTree.firstElementChild;
    if (elNode != null && elNode.className === 'el-tree-node is-expanded is-focusable') {
      // debugger
      let val = treeRef.value.$el.firstElementChild.clientWidth
      leftWidth.value =  val + 60 - 3;
      // debugger
      console.log("宽度已变化");
      // watch(()=>{
      //   return parentRef.value.$el.firstElementChild.clientWidth;
      // },(value)=>{
      //   console.log("宽度已变化2");
      //   debugger
      //   leftWidth.value = (value + 60);
      //   console.log(leftWidth.value);
      // },{immediate: true})
      // watchEffect(() => {
      //   // 获取子元素的宽度
      //   if (parentRef.value.$el.firstElementChild) {
      //     console.log(parentRef.value.$el.firstElementChild)
      // debugger
      // console.log(parentRef.value.el$)
      // const childWidth = parentRef.value.clientWidth;
      // leftWidth.value = parentRef.value.$el.firstElementChild.clientWidth;
      // console.log('子元素的宽度：', childWidth);
      //   }
      // });
    }
  }

}
</script>
<style scoped>
.treeSpan{
  background-color: #0b79ee;
}
/*:deep(.el-form .el-select .el-input__wrapper) {*/
/*  background-color: #409eff;*/
/*}*/

/*:deep(.el-form .el-select .el-input__inner) {*/
/*  color: #ffffff;*/
/*}*/
:deep(.el-form-item__label) {
  display: inline-flex;
  justify-content: flex-end;
  align-items: flex-start;
  flex: 0 0 auto;
  font-size: var(--el-form-label-font-size);
  color: #ffffff;
  height: 32px;
  line-height: 32px;
  padding: 0 12px 0 12px;
  box-sizing: border-box;
  background: #6096e6;
  border-radius: 6px;
  margin-left: 10px;
  margin-right: 10px;
}

.common_style{
  background-color: #daecf8;
}

:deep(.el-tree>.el-tree-node) {
  min-width:100%;
  display: inline-block;
}

.draggable {
  margin-top: 18px;
  width: 5px; /* 设置竖线的宽度 */
  /*height: 100%; !* 设置竖线的高度 *!*/
  background-color: #ffffff; /* 设置竖线的颜色 */
  /*position: absolute;*/
  /*top: 0;*/
  /*left: 50%; !* 设置竖线在页面中的位置 *!*/
  /*transform: translateX(-50%); !* 将竖线居中对齐 *!*/
  z-index: 999; /* 确保竖线位于其他元素之上 */
  /*cursor: ew-resize;*/
  cursor: col-resize;
  /*resize: horizontal;*/
}
.draggable:hover{
  /* 设置光标样式为左右调整大小 */
  /*cursor: ew-resize;*/
  background-color: #595454;
}
.draggable:active{
  /* 设置光标样式为左右调整大小 */
  /*cursor: ew-resize;*/
  background-color: #595454;
}

/* 禁用文本选择 */
.textSelect {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}


</style>
